package cn.edu.zucc.JavaChat.ChatServer.DB.DAO.Imp;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.edu.zucc.JavaChat.ChatServer.DB.DAO.HistoryChatDAO;
import cn.edu.zucc.JavaChat.ChatServer.DB.Entity.HistoryChat;

public class HistoryChatDAOImp extends AbstractDAO implements HistoryChatDAO{

	@Override
	public int saveHistoryChat(String fromUsername, String toUsername,
			String message) {
		String sql = "insert into History(UserID,toUserName,Context,Date) values('"+fromUsername+"','"+toUsername+"','"+message+"',"+new Date()+")";
		this.DBOperationUpdate(sql);
		return 0;
	}


	
	public List<HistoryChat> findByUsername(String toUsername,String fromUsername) {
		String sql = "select * from History where toUserName='"+toUsername+"' and UserID='"+fromUsername+"'";
		//ResultSet rs = this.DBOperationQuery(sql);
		ResultSet rs = null;
		List<HistoryChat> historyList = new ArrayList<HistoryChat>();
		try {
			while(rs.next()){
				HistoryChat historyChat = new HistoryChat();
				historyChat.setFromUsername(rs.getString(2));
				historyChat.setToUsername(rs.getString(3));
				historyChat.setMessage(rs.getString(4));
				historyChat.setChatDate(rs.getDate(5));
				historyList.add(historyChat);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return historyList;
	}



	@Override
	public List<HistoryChat> findByTime(String toUsername, String fromUsername,
			Date startTime, Date endTime) {
		// TODO Auto-generated method stub
		String sql = "select * from History where toUsername='"+toUsername+"' and UserID='"+fromUsername+"' and Date <='" +endTime+"' and Date>='"+startTime+"'";
		//ResultSet rs = this.DBOperationQuery(sql);
		ResultSet rs = null;
		List<HistoryChat> historyList = new ArrayList<HistoryChat>();
		try {
			while(rs.next()){
				HistoryChat historyChat = new HistoryChat();
				historyChat.setFromUsername(rs.getString(2));
				historyChat.setToUsername(rs.getString(3));
				historyChat.setMessage(rs.getString(4));
				historyChat.setChatDate(rs.getDate(5));
				historyList.add(historyChat);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return historyList;
	}

}
